<?php
/**
 * UsersIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 * 
 * @package Users
 * @author j.m.j.s. (25/07/2009)
 */
class UsersIdentity extends CUserIdentity
{
	private $_id;
	
	/**
	 * Por aqui se recibe la llave para encriptar
	 */
	public $rijndaelKey;

	/**
	 * @return unknown_type
	 */
	public function authenticate()
	{
        $username = strtolower($this->username);
        
        $criteria = new CDbCriteria;
        $criteria->condition = "LOWER(usr_nickname)='{$username}' AND usr_status = 1";
        // Se obtiene el registro que coincide con el nombre de usuario
        $user=User::model()->find($criteria);
        
        $rijndael = new RijndaelHex($this->rijndaelKey);
        // Se encripta el password para compararlo con la BD    
        $cryptPassword = $rijndael->linencrypthexComplex($this->password, $this->username);
        
        if($user===null)// Si se encontró al usuario...
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        else if($cryptPassword!=$user->usr_password)// Si el password no coincide
        	$this->errorCode=self::ERROR_PASSWORD_INVALID;
        else//Si el usuario y contraseña son correctos
        {
            $this->_id = $user->usr_code;
            $this->username=$user->usr_nickname;
            $this->setState('usr_profile', $user->usr_profile);
            $this->setState('name', $user->usr_name);
            $this->setState('rol', $user->usr_profile);
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
	}

    /**
     * @return integer
     */
    public function getId()
    {
        return $this->_id;
    }
}